package io.github.bigbird0101.youyishi.code.compile.support;

import cn.hutool.core.compiler.CompilerUtil;
import cn.hutool.core.compiler.JavaSourceCompiler;
import cn.hutool.core.util.StrUtil;
import io.github.bigbird0101.youyishi.code.CodeContent;
import io.github.bigbird0101.youyishi.code.compile.CodeMetadata;
import io.github.bigbird0101.youyishi.code.compile.Compiler;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.stream.Collectors;

/**
 * jdk编译
 */
@Slf4j
public class JdkCompiler implements Compiler {
    /**
     * 是一个完整的字符串 就使用jdk编译器
     *
     * @param codeContentsList 原生的代码
     * @return 是否匹配
     */
    @Override
    public boolean match(List<CodeContent<?>> codeContentsList) {
        return codeContentsList.stream().allMatch(s -> s.getContent() instanceof String);
    }

    @Override
    public List<CodeMetadata> compileCode(List<CodeContent<?>> codeContentsList) {
        JavaSourceCompiler compiler = CompilerUtil.getCompiler(null);
        codeContentsList.stream().filter(s -> StrUtil.isAllNotBlank(s.getClassName(), (CharSequence) s.getContent()))
                .forEach(s -> compiler.addSource(s.getClassName(), (String) s.getContent()));
        try {
            ClassLoader compile = compiler.compile();
            return codeContentsList.stream().map(s -> {
                try {
                    return new CodeMetadata(s.getClassName(), compile.loadClass(s.getClassName()), s);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }).collect(Collectors.toList());
        } catch (Exception e) {
//            log.error(e);
            throw new RuntimeException(e);
        }
    }
}